package util

import (
    "fmt"
    "strconv"
    "strings"

    log "github.com/sirupsen/logrus"
    v1 "k8s.io/api/core/v1"
)

const (
    Default = "default"
)

func Str2int64WithError(str string) (int64, error) {
    str = strings.TrimSpace(str)
    i, err := strconv.ParseInt(str, 10, 64)
    if err != nil {
        return 0, err
    }
    return i, nil
}

func Str2int32WithError(str string) (int32, error) {
    str = strings.TrimSpace(str)
    i, err := strconv.ParseInt(str, 10, 32)
    if err != nil {
        return 0, err
    }
    return int32(i), nil
}

func Str2int32(str string) int32 {
    str = strings.TrimSpace(str)
    i, err := strconv.ParseInt(str, 10, 32)
    if err != nil {
        log.Error("str convert to int32 error", err.Error())
    }
    return int32(i)
}

func MergeNamespaceAndName(namespace, name string) string {
    return fmt.Sprintf("%s/%s", namespace, name)
}

func SplitNamespaceAndName(fullName string) (namespace string, name string) {
    fullName = strings.TrimSpace(fullName)
    index := strings.Index(fullName, "/")
    if index == -1 {
        return Default, fullName
    }
    return fullName[:index], fullName[index+1:]
}

func GetIpListFromEndpoints(endpoints *v1.Endpoints) []string {
    var ipList []string
    for _, subset := range endpoints.Subsets {
        for _, address := range subset.Addresses {
            ipList = append(ipList, address.IP)
        }
    }
    return ipList
}
